/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Yahtzee;

/**
 *
 * @author agreseth
 */
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class MultiServerThread extends Thread {
    
    private Socket socket = null;
    PrintWriter out;
    BufferedReader in;
    String inputLine, outputLine;
    int finalScore;
    int finalScoreStart;
    int finalScoreEnd;
    String scoreStart = "Final Score";
    String scoreEnd = "<end>";
    ServerGUI gui;
    MultiServer serv;
    String player1IP;
    String player2IP;
    String ipadr;

    Scoreboard playerBoard;

    public MultiServerThread(Socket funSocket, ServerGUI gu, MultiServer serv)
    {
        super("MultiServerThread");
        this.socket = funSocket;
        this.gui = gu;
        this.serv = serv;
        playerBoard = new Scoreboard();
    }
    

    public void run()
    {
        try
        {
            
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //insert the yahtzee protocol code after actually making it...


            // loop around getting input from client
            while(true)
            {
            String check = recv();

            System.out.println(check);
            if (check.startsWith("Start"))
            {
                gui.messagesTextArea.append("\nA game is starting!");
                int startIP = check.indexOf("/");
                int endIP = check.indexOf("^");
                int end = check.indexOf(scoreEnd);
                player1IP = check.substring(startIP+1,endIP);
                player2IP = check.substring(endIP+1,end);
                int game = serv.setUpGame(player1IP, player2IP);


                if (game == 1)
                {
                    //notify the other player so that the game can begin.
                    //possibly block now so that the thread will sit in this state
                    // and allow for interaction in the game itself
                    System.out.println("Game Set");
                    gui.messagesTextArea.append("\nThis match will be between " + player1IP + " and " + player2IP);
                    gameStarted();
                }
            }
            // tempory fix to get the actual score input
            else if(!check.startsWith("/"))
            {
                gameStarted();
            }

            else
            {
            //out.println(ips);
            ipadr = check;
            gui.messagesTextArea.setText(ipadr);
            serv.addIP(ipadr);
            
            }

            System.out.println("In the run method...");
            //out.println(socket.getLocalAddress());
            
            //String result = in.readLine();
            //System.out.println(result);
            // set this up to grab something that signifies final score
            //finalScoreStart = result.indexOf(scoreStart);
            //System.out.println(finalScoreStart);
            //finalScoreEnd = result.indexOf(scoreEnd);
            //System.out.println(finalScoreEnd);
            // final score
            //String score = result.substring(finalScoreStart+12, finalScoreEnd-1);
            //System.out.println(score);
            //finalScore = Integer.parseInt(score);
            //this.gui.messagesTextArea.append(score+"\n");
            //System.out.println(finalScore);
            //out.println(finalScore);
            //System.out.println(socket.getInetAddress().toString());
            //serv.setIP(socket.getInetAddress().toString());


            // update the list of ips on the main server
            String temp[] = serv.getList();
            //System.out.println(temp[0]);
            String ips = "";
            int i = 0;
            while (temp[i] != null)
            {
                ips += temp[i];
                i++;
            }
            
            out.println(i + ips);
            gui.messagesTextArea.append(ips);


            // checking if it will still send to old thread *works*
//            try
//            {
//                sleep(10000);
//                out.println("I'm Back");
//                System.out.println("I'm Back");
//            }
//            catch(Exception e)
//            {
//
//            }
//            if (yo == 0)
//            {
//            while(true)
//            {
//            if(checkWait(ipadr)==1)
//            {
//                out.println("Game On");
//                break;
//            }
//            System.out.println("Working baby");
//            try{
//            sleep(3000);
//            }
//            catch(Exception e)
//            {
//
//            }
//            }
//
//        }
            }
        }
        
        catch (IOException e)
        {
            
        }
        
    }
    // gets the finalscore
    public int getFinalScore()
    {
        return finalScore;
    }

    // let the client know they got an opponent
    public void startGame(String ip)
    {
        out.println("Game On"+ip);
//        gameStarted();
    }
    public void close()
    {
        try
        {
            in.close();
            out.close();
            socket.close();
        }
        catch (Exception e)
        {
            System.out.println("Awww man...closing didn't work!");
        }
    }

    // game has started to start processing the scores received
    public void gameStarted()
    {
        
        System.out.println("Game Started I think");
        
        while(true)
        {
            System.out.println("In Loop");
            
            
                String s = recv();
                System.out.println(s+"yes i am s");
                
//                if (s.startsWith("Ones"))
//                {
//                    System.out.println("I started with ones");
//                    int score = 5;
//                    serv.setOnes(ipadr,score);
//                }
//                else
//                {
//                    System.out.println("Hold on me boy");
//                }
            
                    
            
        }
        
    }

    // send to the client associated with this thread the score
    public void send(String category,int score)
    {
        out.println(category+score);
    }


    // receive info from client, will determine if a score occured or if it is just
    // a simple command
    public String recv()
    {
        String input = "";
        try
        {
            input = in.readLine();
            if(input.contains("Ones"))
            {
                int score = Integer.parseInt(input.substring(4));
                serv.setScores(ipadr, score,"Ones");
                playerBoard.setScores(0, score);
            }
            else if(input.contains("Twos"))
            {
                int score = Integer.parseInt(input.substring(4));
                serv.setScores(ipadr, score,"Twos");
                playerBoard.setScores(1, score);
            }
            else if(input.contains("Threes"))
            {
                int score = Integer.parseInt(input.substring(6));
                serv.setScores(ipadr, score,"Threes");
                playerBoard.setScores(2, score);
            }
            else if(input.contains("Fours"))
            {
                int score = Integer.parseInt(input.substring(5));
                serv.setScores(ipadr,score,"Fours");
                playerBoard.setScores(3, score);
            }
            else if(input.contains("Fives"))
            {
                int score = Integer.parseInt(input.substring(5));
                serv.setScores(ipadr, score,"Fives");
                playerBoard.setScores(4, score);
            }
            else if(input.contains("Sixes"))
            {
                int score = Integer.parseInt(input.substring(5));
                serv.setScores(ipadr, score,"Sixes");
                playerBoard.setScores(5, score);
            }
            else if(input.contains("ThreeKind"))
            {
                int score = Integer.parseInt(input.substring(9));
                serv.setScores(ipadr, score,"ThreeKind");
                playerBoard.setScores(6, score);
            }
            else if(input.contains("FourKind"))
            {
                int score = Integer.parseInt(input.substring(8));
                serv.setScores(ipadr, score,"FourKind");
                playerBoard.setScores(7, score);
            }
            else if(input.contains("FullHouse"))
            {
                int score = Integer.parseInt(input.substring(9));
                serv.setScores(ipadr, score,"FullHouse");
                playerBoard.setScores(8, score);
            }
            else if(input.contains("SmallStraight"))
            {
                int score = Integer.parseInt(input.substring(13));
                serv.setScores(ipadr, score,"SmallStraight");
                playerBoard.setScores(9, score);
            }
            else if(input.contains("LargeStraight"))
            {
                int score = Integer.parseInt(input.substring(13));
                serv.setScores(ipadr, score,"LargeStraight");
                playerBoard.setScores(10, score);
            }
            else if(input.contains("Yahtzee") & (input.length() < 10))
            {
                int score = Integer.parseInt(input.substring(7));
                serv.setScores(ipadr, score,"Yahtzee");
                playerBoard.setScores(11, score);
            }
            else if(input.contains("Chance"))
            {
                int score = Integer.parseInt(input.substring(6));
                serv.setScores(ipadr, score,"Chance");
                playerBoard.setScores(12, score);
            }
            else if(input.contains("UpperScore"))
            {
                int score = Integer.parseInt(input.substring(10));
                serv.setScores(ipadr,score, "UpperScore");
            }
            else if(input.contains("Bonus") & (input.length() < 10))
            {
                int score = Integer.parseInt(input.substring(5));
                serv.setScores(ipadr, score, "Bonus");
            }
            else if(input.contains("YahtzeeBonus"))
            {
                System.out.println("Made it to YahtzeeBonus else if...");
                int score = 0;
                if (input.substring(12) != null)
                {
                    System.out.println("Made it inside next YahtzeeBonus if..." + input);
                    score = Integer.parseInt(input.substring(12));
                    System.out.println(score);
                }
                
                
              
                serv.setScores(ipadr, score, "YahtzeeBonus");
            }
            else if(input.contains("TotalScore"))
            {
                int score = Integer.parseInt(input.substring(10));
                serv.setScores(ipadr, score, "TotalScore");
            }
            else if(input.contains("LowerScore"))
            {
                int score = Integer.parseInt(input.substring(10));
                serv.setScores(ipadr,score,"LowerScore");
            }
            else if(input.contains("FinalScore"))
            {
                int score = Integer.parseInt(input.substring(10));
            }
        }
        catch(Exception e)
        {
            System.out.println("Receive" + e.getMessage());
        }
        return input;
    }
    
}